<template>
  <div class="login-page">
    <!-- 背景图容器 -->
    <div class="bg-container">
      <img
          src="../assets/img.png"
          alt="背景图"
          class="bg-img"
      />
    </div>

    <!-- 登录卡片容器 -->
    <div class="login-card">
      <div class="left-panel">
        <div class="welcome-wrapper">
          <p class="welcome-line1">欢迎登录抢票系统</p>
          <p class="welcome-line2">祝您抢票愉快</p>
        </div>
      </div>
      <div class="right-panel">
        <!-- 登录类型选择 -->
        <div class="login-type-selector">
          <el-radio-group v-model="loginType" @change="switchLoginType">
            <el-radio-button label="user">用户登录</el-radio-button>
            <el-radio-button label="admin">管理员登录</el-radio-button>
          </el-radio-group>
        </div>

        <el-form
            ref="loginFormRef"
            :model="user"
            class="login-form"
        >
          <!-- 用户登录字段 -->
          <template v-if="loginType === 'user'">
            <el-form-item>
              <el-input
                  v-model="user.phone"
                  placeholder="请输入手机号"
                  :prefix-icon="User"
                  maxlength="11"
                  class="custom-input"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                  v-model="user.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                  :prefix-icon="Lock"
                  maxlength="16"
                  class="custom-input"
              />
            </el-form-item>
            <el-form-item class="captcha-group">
              <el-input
                  v-model="user.captcha"
                  placeholder="验证码"
                  :prefix-icon="Key"
                  maxlength="4"
                  class="captcha-input"
              />
              <img
                  :src="captcha"
                  class="captcha-img"
                  @click="loadCaptcha"
                  title="点击刷新"
              >
            </el-form-item>
          </template>

          <!-- 管理员登录字段 -->
          <template v-else>
            <el-form-item>
              <el-input
                  v-model="user.adminAccount"
                  placeholder="请输入管理员账号"
                  :prefix-icon="User"
                  maxlength="20"
                  class="custom-input"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                  v-model="user.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                  :prefix-icon="Lock"
                  maxlength="16"
                  class="custom-input"
              />
            </el-form-item>
          </template>

          <el-form-item>
            <el-button
                type="primary"
                class="login-btn"
                @click="onSubmit"
            >
              登录
            </el-button>
          </el-form-item>

          <!-- 只在用户登录时显示额外功能 -->
          <div class="extra-buttons" v-if="loginType === 'user'">
            <el-button
                type="text"
                class="extra-btn"
                @click="showForgotPwdDialog = true"
            >
              忘记密码
            </el-button>
            <el-button
                type="text"
                class="extra-btn"
                @click="showRegisterDialog = true"
            >
              注册
            </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 忘记密码弹窗 -->
    <el-dialog
        title="忘记密码"
        v-model="showForgotPwdDialog"
        width="30%"
    >
      <el-form
          ref="forgotPwdFormRef"
          :model="forgotPwdForm"
          :rules="forgotPwdRules"
          class="forgot-pwd-form"
      >
        <el-form-item prop="phone">
          <el-input
              v-model="forgotPwdForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
          />
        </el-form-item>
        <el-form-item prop="realname">
          <el-input
              v-model="forgotPwdForm.realname"
              placeholder="请输入真实姓名"
          />
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
              v-model="forgotPwdForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
              v-model="forgotPwdForm.confirmPassword"
              type="password"
              placeholder="请确认新密码"
              show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showForgotPwdDialog = false">取消</el-button>
          <el-button type="primary" @click="handleResetPassword">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
        title="用户注册"
        v-model="showRegisterDialog"
        width="30%"
    >
      <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="register-form"
      >
        <el-form-item prop="phone">
          <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              show-password
          />
        </el-form-item>
        <el-form-item prop="realname">
          <el-input
              v-model="registerForm.realname"
              placeholder="请输入真实姓名"
          />
        </el-form-item>
        <el-form-item prop="idcard">
          <el-input
              v-model="registerForm.idcard"
              placeholder="请输入身份证号"
              maxlength="18"
          />
        </el-form-item>
        <el-form-item prop="nickname">
          <el-input
              v-model="registerForm.nickname"
              placeholder="请输入昵称"
              maxlength="18"
          />nickname
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRegisterDialog = false">取消</el-button>
          <el-button type="primary" @click="handleRegister">
            注册
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton, ElDialog, ElRadioGroup, ElRadioButton } from 'element-plus';
import { useRouter } from 'vue-router';
import { Lock, Key, User } from '@element-plus/icons-vue';
import loginApi from '../api/login_api.js';

// 登录类型：user或admin
const loginType = ref('user');

// 登录表单数据
const user = ref({
  phone: '',
  adminAccount: '',
  password: '',
  captcha: '',
  key: ''
});

// 验证码
const captcha = ref('');

// 忘记密码表单数据
const forgotPwdForm = reactive({
  phone: '',
  realname: '',
  newPassword: '',
  confirmPassword: ''
});

// 忘记密码表单校验规则
const forgotPwdRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  realname: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        if (value !== forgotPwdForm.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 注册表单数据
const registerForm = reactive({
  phone: '',
  password: '',
  confirmPassword: '',
  realname: '',
  idcard: '',
  nickname:''
});

// 注册表单校验规则
const registerRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  realname: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  idcard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
};

// 控制弹窗显示隐藏的变量
const showForgotPwdDialog = ref(false);
const showRegisterDialog = ref(false);

// 表单引用
const loginFormRef = ref(null);
const forgotPwdFormRef = ref(null);
const registerFormRef = ref(null);

const router = useRouter();

onMounted(() => {
  loadCaptcha();
});

// 切换登录类型
const switchLoginType = () => {
  // 清空表单
  user.value.phone = '';
  user.value.adminAccount = '';
  user.value.password = '';
  user.value.captcha = '';
};

// 处理登录
const onSubmit = async () => {
  try {
    if (loginType.value === 'user') {
      // 用户登录校验
      if (!user.value.phone || !user.value.password || !user.value.captcha) {
        ElMessage.error('请填写完整登录信息');
        return;
      }

      // 调用用户登录API
      const res = await loginApi.userLogin({
        phone: user.value.phone,
        password: user.value.password,
        captcha: user.value.captcha,
        key: user.value.key
      });

      if (res) {
        localStorage.setItem('token', res);
        localStorage.setItem('userType', 'user');
        ElMessage.success('用户登录成功，正在跳转...');
        router.push('/'); // 跳转到演唱会首页
      }
    } else {
      // 管理员登录校验
      if (!user.value.adminAccount || !user.value.password) {
        ElMessage.error('请填写管理员账号和密码');
        return;
      }
      console.log(user.value);
      // 调用管理员登录API
      const res = await loginApi.adminLogin({
        adminAccount: user.value.adminAccount,
        password: user.value.password
      });

      if (res) {
        localStorage.setItem('token', res);
        localStorage.setItem('userType', 'admin');
        ElMessage.success('管理员登录成功，正在跳转...');
        router.push('/index'); // 跳转到管理后台
      }
    }
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请检查账号密码或验证码');
    if (loginType.value === 'user') {
      loadCaptcha();
    }
  }
};

// 加载验证码
const loadCaptcha = async () => {
  try {
    const res = await loginApi.captcha();
    user.value.key = res.key;
    captcha.value = res.base;
  } catch (error) {
    ElMessage.error('验证码加载失败，请重试');
  }
};

// 处理重置密码
const handleResetPassword = () => {
  forgotPwdFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用忘记密码API，验证手机号和真实姓名是否匹配
        const res = await loginApi.resetPassword({
          phone: forgotPwdForm.phone,
          realname: forgotPwdForm.realname,
          newPassword: forgotPwdForm.newPassword
        });

        if (res) {
          ElMessage.success('密码重置成功，请使用新密码登录');
          showForgotPwdDialog.value = false;
        }
      } catch (error) {
        ElMessage.error(error.message || '密码重置失败');
      }
    } else {
      ElMessage.error('请填写完整并符合规则的信息');
      return false;
    }
  });
};

// 处理注册
const handleRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用注册API
        const res = await loginApi.register({
          phone: registerForm.phone,
          password: registerForm.password,
          realname: registerForm.realname,
          idcard: registerForm.idcard
        });

        if (res) {
          ElMessage.success('注册成功，请登录');
          showRegisterDialog.value = false;
        }
      } catch (error) {
        ElMessage.error(error.message || '注册失败');
      }
    } else {
      ElMessage.error('请填写完整并符合规则的注册信息');
      return false;
    }
  });
};
</script>

<style scoped>
.login-page {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.bg-container {
  width: 100%;
  height: 100%;
}

.bg-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.login-card {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 800px;
  height: 450px;
  display: flex;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.8);
  border-radius: 8px;
  overflow: hidden; /* 隐藏超出卡片的内容 */
}

.left-panel {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.1); /* 左侧更高的透明度 */
  padding: 20px;
}

.welcome-wrapper {
  text-align: center;
}

.welcome-line1 {
  font-size: 35px;
  color: #333;
  margin-bottom: 10px;
  font-weight: bold;
}

.welcome-line2 {
  font-size: 22px;
  color: #333;
  margin-bottom: 10px;
  font-weight: bold;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.7); /* 右侧稍低的透明度 */
  padding: 20px;
}

.login-type-selector {
  margin-bottom: 20px;
}

.login-form {
  width: 100%;
  max-width: 300px;
}

.custom-input,
.captcha-input {
  height: 50px;
  border-radius: 8px;
  border-color: #e5e7eb;
  transition: all 0.3s ease;
}

.custom-input:hover,
.custom-input:focus-within,
.captcha-input:hover,
.captcha-input:focus-within {
  border-color: #a5dee5;
  box-shadow: 0 0 0 3px rgba(165, 222, 229, 0.2);
}

.captcha-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-img {
  width: 100px;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
}

.captcha-img:hover {
  transform: scale(1.02);
}

.login-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: #a5dee5;
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: #ffb6b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(252, 182, 217, 0.3);
}

.login-btn:active {
  transform: translateY(0);
}

.extra-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.extra-btn {
  padding: 0;
}

.forgot-pwd-form,
.register-form {
  width: 100%;
}
</style>
